
import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma.service';
import { User, Prisma } from '@prisma/client';
import { TRes } from '../common/base';

@Injectable()
export class UserService {
  constructor(private prisma: PrismaService) { }


  async getUser(
    userWhereUniqueInput: Prisma.UserWhereUniqueInput,
  ): Promise<TRes<User>> {
   try {
    const user = await this.prisma.user.findUnique({
      where: userWhereUniqueInput,
    });
    return {
      // @ts-ignore
      data: user,
      msg: '查询用户成功'
    }
   } catch (error) {
    return {
      msg: error,
      data: null,
      sql: true
    }
   }
  }

  async getUsers(userIds: string): Promise<TRes<User[]>> {
    try {
      const arr = userIds.split(',')
      const userArr = []
      for (const userId of arr) {
        const data = await this.prisma.user.findUnique({
          where: {
            userId: userId
          }
        })
        userArr.push(data)
      }
      return {
        data: userArr,
      }
    } catch (error) {
      return {
        msg: error,
        data: null,
        sql: true // 执行sql失败
      }
    }
  }

  async updateUername(param: Pick<User, 'userId' | 'username'>) {
    try {
      const res = await this.prisma.user.update({
        where: {
          userId: param.userId
        },
        data: {
          username: param.username
        }
      })
      return {
        msg: '更新用户名成功',
        data: res
      }

    } catch (error) {
      return {
        msg: error,
        data: null,
        sql: true
      }
    }
  }

  async updateUser(params: {
    where: Prisma.UserWhereUniqueInput;
    data: Prisma.UserUpdateInput;
  }): Promise<User> {
    const { where, data } = params;
    return this.prisma.user.update({
      data,
      where,
    });
  }

  async deleteUser(where: Prisma.UserWhereUniqueInput): Promise<User> {
    return this.prisma.user.delete({
      where,
    });
  }
}
